package rexsee.core.browser.clazz;

import java.util.ArrayList;

import rexsee.core.application.RexseeApplication;
import rexsee.core.browser.Browser;
import rexsee.core.browser.RexseePregFilter;
import rexsee.core.lang.RexseeLanguage;
import android.content.Context;

public class PregFilterListener extends FilterListener {
	public final ArrayList<PregPair> pregPairs;
	public PregFilterListener(String name) {
		super(name, RexseePregFilter.PREG_FILTER_TYPE);
		pregPairs = new ArrayList<PregPair>();
	}
	@Override
	public void run(final Context context, final Browser browser, final String url) {
		new Thread() {
			@Override
			public void run() {
				String code = browser.urlListeners.getContent(url);
				browser.progressDialog.show(RexseeLanguage.PROGRESS_ONGOING);
				if (code.startsWith(RexseeApplication.EXCEPTION_PREFIX)) {
					browser.progressDialog.hide();
					browser.exception("PregFilterListener", code);
				} else {
					for (int i = 0; i < pregPairs.size(); i++) {
						PregPair pair = pregPairs.get(i);
						code = code.replaceAll(pair.source, pair.replacement);
					}
					if (RexseePregFilter.mIsDebuging) browser.application.alert(code);
					browser.loadDataWithBaseURL(url, code, "text/html", "UTF-8", url);
					browser.history.add(url);
				}
			}
		}.start();
	}
	public boolean containsPair(PregPair pair) {
		return pregPairs.contains(pair);
	}
	public void addPair(PregPair pair) {
		pregPairs.add(pair);
	}
	public String getPairs() {
		String rtn = "";
		for (int i = 0; i < pregPairs.size(); i++) {
			PregPair pair = pregPairs.get(i);
			if (i > 0) rtn += ",";
			rtn += "{";
			rtn += "\"source\":\"" + pair.source + "\"";
			rtn += ",\"replacement\":\"" + pair.replacement + "\"";
			rtn += "}";
		}
		rtn = "[" + rtn + "]";
		return rtn;
	}
	public int getNumberOfPairs() {
		return pregPairs.size();
	}
	public void clearPairs() {
		pregPairs.clear();
	}
}
